//
//  GoodsAttributePopView.m
//  TerritoryShopkeeper
//
//  Created by 黄德玉 on 2018/6/7.
//  Copyright © 2018年 ZDQK. All rights reserved.
//

#import "GoodsAttributePopView.h"
#import <Masonry/Masonry.h>
#import "GoodDetailModel.h"
#import "CartCountControlView.h"

@interface _GoodsAttributePopBtmView : UIView

@property (nonatomic,strong) UIButton * addCartBtn; //加入购物车按钮
@property (nonatomic,strong) UIButton * buyBtn;     //买入按钮
@property (nonatomic,copy) void(^didClickedBtmBlock)(NSInteger tag);//0 加入购物车， 1：立即购买
@end

@implementation _GoodsAttributePopBtmView

- (instancetype)init{
    if (self = [super init]) {
        self.addCartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addCartBtn setBackgroundImage:[UIImage imageWithColor:[UIColor yellowButtonColor]] forState:UIControlStateNormal];
        [_addCartBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _addCartBtn.titleLabel.font = TextPingFangFontSize(14);
        [_addCartBtn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_addCartBtn setTitle:@"加入购物车" forState:UIControlStateNormal];
        _addCartBtn.tag = 0;
        
        self.buyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_buyBtn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_buyBtn setBackgroundImage:[UIImage imageWithColor:[UIColor orangePriceColor]] forState:UIControlStateNormal];
        [_buyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _buyBtn.titleLabel.font = TextPingFangFontSize(14);
        [_buyBtn setTitle:@"立即购买" forState:UIControlStateNormal];
        _buyBtn.tag = 1;
        
        [self addSubview:self.addCartBtn];
        [self addSubview:self.buyBtn];
    }
    return self;
}

- (void)setupWithType:(GoodsAttributePopType)type{
    switch (type) {
        case GoodsAttributePopTypeCommon:{
            [self.addCartBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.top.bottom.equalTo(self);
                make.width.equalTo(self).multipliedBy(.5);
            }];
            [self.buyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.right.bottom.equalTo(self);
                make.width.equalTo(self).multipliedBy(.5);
            }];
        }
            break;
        case GoodsAttributePopTypeBuy:{
            [self.buyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(self);
            }];
            self.addCartBtn.hidden = YES;
        }
            break;
        case GoodsAttributePopTypeAddCart:{
            [self.addCartBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(self);
            }];
            self.buyBtn.hidden = YES;
        }
            break;
        default:
            break;
    }
}

- (void)buttonClick:(UIButton *)btn{
    if (self.didClickedBtmBlock) {
        self.didClickedBtmBlock(btn.tag);
    }
}

@end

///////////////////////////////////////////////////////
////////////////////////////////////////////////////////


@interface _GoodsAttributePopAddView : UIView<UITextFieldDelegate>

@property (nonatomic,strong) UIButton * desBtn;
@property (nonatomic,strong) UIButton * addBtn;
@property (nonatomic,strong) UITextField * textField;
@property (nonatomic,strong) void(^valueChangedBlock)(UITextField * textField);

@end

@implementation _GoodsAttributePopAddView

- (instancetype)init{
    if (self = [super init]) {
        self.backgroundColor = [UIColor grayF9Color];
        self.desBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.desBtn setImage:[UIImage imageNamed:@"reduce"] forState:UIControlStateNormal];
        [self.desBtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
        _desBtn.tag = 0;
        
        self.addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addBtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
        _addBtn.tag = 1;
        [self.addBtn setImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
        
        self.textField = [UITextField new];
        self.textField.keyboardType = UIKeyboardTypeNumberPad;
        _textField.textAlignment = NSTextAlignmentCenter;
        _textField.font = TextPingFangFontSize(14);
        _textField.text = @"0";
        _textField.delegate = self;
        _textField.returnKeyType = UIReturnKeyDone;
        
        [self addSubview:self.desBtn];
        [self addSubview:self.addBtn];
        [self addSubview:self.textField];
        [self _layout];
    }
    return self;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    textField.text = [NSString stringWithFormat:@"%ld",[textField.text integerValue]];
    if (self.valueChangedBlock) {
        self.valueChangedBlock(textField);
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.textField endEditing:YES];
    return YES;
}

- (void)btnClicked:(UIButton *)btn{
    NSInteger value = [self.textField.text integerValue];
    if (btn.tag == 0) {
        value--;
        if (value < 0) {
            value = 0;
        }
        self.textField.text = [NSString stringWithFormat:@"%ld",value];
    }else{
        self.textField.text =[NSString stringWithFormat:@"%ld",value+1];
    }
    if (self.valueChangedBlock) {
        self.valueChangedBlock(self.textField);
    }
}

- (void)_layout{
    [self.desBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(self);
        make.width.equalTo(@32);
        make.height.equalTo(@32);
    }];
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.desBtn.mas_right);
        make.right.equalTo(self.addBtn.mas_left);
        make.top.bottom.equalTo(self);
        make.width.equalTo(@40);
    }];
    [self.addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.equalTo(self);
        make.width.equalTo(@32);
    }];
}

@end


/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////






@interface GoodsAttributePopView()

@property (nonatomic,strong) UIButton * closeBtn;
@property (nonatomic,strong) UIControl * bgTouchView;
@property (nonatomic,strong) UIView * bgWhiteView;
@property (nonatomic,strong) UIImageView * goodsImgView;
@property (nonatomic,strong) UILabel * goodsDesLabel;
@property (nonatomic,strong) UILabel * moneyLabel;
@property (nonatomic,strong) UILabel * amountLabel;

@property (nonatomic,strong) UIScrollView * scrollView;
@property (nonatomic,strong) UIView *  scrollContentView;

@property (nonatomic,strong) UILabel * countDesc; //数量
@property (nonatomic,strong) _GoodsAttributePopAddView * addCountView;   //+ - UI

@property (nonatomic,strong) _GoodsAttributePopBtmView * btmView;   //底部的加入购物车和立即购买按钮

@property (nonatomic,strong) id colorData;                      //点选的color数据
@property (nonatomic,strong) id skuData;                        //点选的sku数据
@property (nonatomic,strong) id fieldsData;                     //计算的field数据
@property (nonatomic,assign) NSInteger kucun;                   //计算的库存数据，在field里
@property (nonatomic,copy) NSString * currentPrice;             //计算的价格数据，在field里

@property (nonatomic,weak) GoodDetailModel * detailModel;

@property (nonatomic,copy) void(^btmClickedBlock)(id data);  //点击交互返回



@end

@implementation GoodsAttributePopView

- (instancetype)init{
    if (self = [super init]) {
        self.backgroundColor = [UIColor clearColor];
        //背景按钮
        self.bgTouchView = [[UIControl alloc] init];
        self.bgTouchView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.5];
        [self.bgTouchView addTarget:self action:@selector(bgTouched) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.bgTouchView];
        [self.bgTouchView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
        //背景白色
        self.bgWhiteView = [UIView new];
        self.bgWhiteView.backgroundColor = [UIColor whiteColor];
        [self addSubview:self.bgWhiteView];
        [self.bgWhiteView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(self);
            make.top.equalTo(self).offset((ScreenHeight * .3));
        }];
        //x按钮
        self.closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.closeBtn setImage:[UIImage imageNamed:@"revoke"] forState:UIControlStateNormal];
        [self.closeBtn addTarget:self action:@selector(bgTouched) forControlEvents:UIControlEventTouchUpInside];
        [self.bgWhiteView addSubview:self.closeBtn];
        [self.closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.bgWhiteView);
            make.top.equalTo(self.bgWhiteView);
            make.width.equalTo(@30);
            make.height.equalTo(@30);
        }];
        
        //商品图片
        self.goodsImgView = [[UIImageView alloc] init];
        self.goodsImgView.contentMode = UIViewContentModeScaleAspectFit;
        self.goodsImgView.backgroundColor = [UIColor lightGrayColor];
        [self.bgWhiteView addSubview:self.goodsImgView];
        [self.goodsImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.bgWhiteView).offset(10);
            make.top.equalTo(self.bgWhiteView).offset(20);
            make.width.height.equalTo(@100);
        }];
        //商品描述
        self.goodsDesLabel = [UILabel new];
        self.goodsDesLabel.font = [UIFont systemFontOfSize:16];
        self.goodsDesLabel.textColor = [UIColor blackTextColor];
        self.goodsDesLabel.numberOfLines = 2;
        [self.bgWhiteView addSubview:self.goodsDesLabel];
        [self.goodsDesLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.goodsImgView).offset(5);
            make.left.equalTo(self.goodsImgView.mas_right).offset(5);
            make.right.equalTo(self.bgWhiteView).offset(-10);
        }];
        //商品价格
        self.moneyLabel = [UILabel new];
        self.moneyLabel.textColor = [UIColor orangePriceColor];
        self.moneyLabel.font = TextPingFangFontSize(14);
        [self.bgWhiteView addSubview:self.moneyLabel];
        [self.moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.goodsImgView.mas_right).offset(5);
            make.bottom.equalTo(self.goodsImgView).offset(-20);
        }];
        
        //库存
        self.amountLabel = [UILabel new];
        self.amountLabel .textColor = [UIColor grayTextColor];
        self.amountLabel .font = TextPingFangFontSize(14);
        [self.bgWhiteView addSubview:self.amountLabel];
        [self.amountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.goodsImgView.mas_right).offset(5);
            make.bottom.equalTo(self.goodsImgView);
        }];
        
        //底部视图
         __weak typeof(self) weakSelf = self;
        self.btmView = [[_GoodsAttributePopBtmView alloc] init];
        self.btmView.didClickedBtmBlock = ^(NSInteger tag) {
            if (weakSelf.detailModel.g_color.count > 0 && !weakSelf.colorData) {//存在颜色，但是没有选择颜色
                [MBProgressHUD showError:weakSelf title:@"请选择颜色" code:@"" animated:YES];
                return;
            }
            if (weakSelf.detailModel.g_sku.count > 0 && !weakSelf.skuData) {//存在sku，但是没有选择sku
                [MBProgressHUD showError:weakSelf title:@"请选择规格" code:@"" animated:YES];
                return;
            }
            if ([weakSelf.addCountView.textField.text integerValue] == 0) {                                      //没有选择数量
                [MBProgressHUD showError:weakSelf title:@"请选择数量" code:@"" animated:YES];
                return;
            }
            if (tag == 0) {//加入购物车点击
                if (weakSelf.btmClickedBlock) {
                    weakSelf.btmClickedBlock(@{@"color":weakSelf.colorData ? weakSelf.colorData : @{},
                                               @"sku":weakSelf.skuData ? weakSelf.skuData : @{},
                                               @"price":weakSelf.fieldsData ? weakSelf.fieldsData : @{},
                                               @"type":@0,
                                               @"count":weakSelf.addCountView.textField.text
                                               });
                }
                
            }else{
                if (weakSelf.btmClickedBlock) {
                    weakSelf.btmClickedBlock(@{@"color":weakSelf.colorData ? weakSelf.colorData : @{},
                                               @"sku":weakSelf.skuData ? weakSelf.skuData : @{},
                                               @"price":weakSelf.fieldsData ? weakSelf.fieldsData : @{},
                                               @"type":@1,
                                               @"count":weakSelf.addCountView.textField.text
                                               });
                }
            }
            [weakSelf bgTouched];//隐藏
        };
        [self.bgWhiteView addSubview:self.btmView];
        [self.btmView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(self.bgWhiteView);
            make.height.equalTo(@50);
        }];
        
        //滚动视图部分
        self.scrollView = [UIScrollView new];
        self.scrollView.showsVerticalScrollIndicator = NO;
        self.scrollView.alwaysBounceVertical = YES;
        [self.bgWhiteView addSubview:self.scrollView];
        [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.bgWhiteView);
            make.top.equalTo(self.goodsImgView.mas_bottom).offset(5);
            make.bottom.equalTo(self).offset(-50);
        }];
        self.scrollContentView = [UIView new];
        [self.scrollView addSubview:self.scrollContentView];
        [self.scrollContentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.scrollView);
            make.width.equalTo(@(ScreenWidth));
        }];
        
        //数量标签
        self.countDesc = [UILabel new];
        self.countDesc.textColor = [UIColor blackTextColor];
        self.countDesc.font = TextPingFangFontSize(16);
        self.countDesc.text = @"数量";
        [self.scrollContentView addSubview:self.countDesc];
        [self.countDesc mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.scrollContentView).offset(10);
            make.top.equalTo(self.scrollContentView).offset(10);
            make.bottom.equalTo(self.scrollContentView).offset(-10).priorityLow();
        }];
        //+ -
        self.addCountView = [[_GoodsAttributePopAddView alloc] init];
       
        self.addCountView.valueChangedBlock = ^(UITextField *textfield) {
            //点选+ - 或者直接编辑文本
            NSInteger vint = [textfield.text integerValue];
            if (vint > weakSelf.kucun) {
                textfield.text = [NSString stringWithFormat:@"%ld",weakSelf.kucun];
                [MBProgressHUD showError:weakSelf title:@"超出库存" code:@"" animated:YES];
            }
        };
        [self.scrollContentView addSubview:self.addCountView];
        [self.addCountView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.countDesc);
            make.right.equalTo(self.scrollContentView).offset(-10);
        }];
    }
    return self;
}

+ (void)showWithData:(id)data popType:(GoodsAttributePopType)type actionCallback:(void (^)(id))callback{
    GoodsAttributePopView * popView = [[GoodsAttributePopView alloc] init];
    [popView.btmView setupWithType:type];
    popView.btmClickedBlock = callback;
    [[UIApplication sharedApplication].keyWindow addSubview:popView];
    [popView _loadData:data];
    popView.frame = [UIApplication sharedApplication].keyWindow.bounds;
    popView.alpha = 0;
    popView.bgWhiteView.transform = CGAffineTransformMakeTranslation(0, ScreenHeight * .7);
    [UIView animateWithDuration:.3 animations:^{
        popView.alpha = 1;
        popView.bgWhiteView.transform = CGAffineTransformIdentity;
    }];
    
}

- (void)_loadData:(GoodDetailModel *)detailModel{
    self.detailModel = detailModel;
    [self.goodsImgView sd_setImageWithURL:[NSURL URLWithString:detailModel.ghomeimg] placeholderImage:PlaceholderImageSmall changeContentModel:UIViewContentModeScaleAspectFill];
    self.goodsDesLabel.text = detailModel.gname;
    self.moneyLabel.text = [NSString stringWithFormat:@"￥%@",detailModel.gprice];
    self.amountLabel.text = @"库存：0";
    GoodsSKUChooseView * chooseView = [[GoodsSKUChooseView alloc] init];//选择颜色
    GoodsSKUChooseView * skuView = [[GoodsSKUChooseView alloc] init];//选择规格
    __weak typeof(self) weakSelf = self;
    if (detailModel.g_color.count > 0) {
        [self.scrollContentView addSubview:chooseView];
        [chooseView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.equalTo(self.scrollContentView);
        }];
        [chooseView loadItems:detailModel.g_color];
        chooseView.didSelectItem = ^(id data) {
            //点选颜色
            weakSelf.colorData = data;
            [weakSelf _updateWithSelectedChanged];
        };
    }
    if (detailModel.g_sku.count == 0) {
        [self.countDesc mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.scrollContentView).offset(10);
            make.top.equalTo(chooseView.mas_bottom).offset(20);
            make.bottom.equalTo(self.scrollContentView).offset(-10).priorityLow();
        }];
    }else{
        [self.scrollContentView addSubview:skuView];
        [skuView loadItems:detailModel.g_sku];
        skuView.didSelectItem = ^(id data) {
            //点选规格
            weakSelf.skuData = data;
            [weakSelf _updateWithSelectedChanged];
        };
        
        [skuView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.scrollContentView);
            if (detailModel.g_color.count > 0) {
                make.top.equalTo(chooseView.mas_bottom).offset(10);
            }else{
                make.top.equalTo(self.scrollContentView);
            }
        }];
        [self.countDesc mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.scrollContentView).offset(10);
            make.top.equalTo(skuView.mas_bottom).offset(20);
            make.bottom.equalTo(self.scrollContentView).offset(-10).priorityLow();
        }];
    }
}

//当选择规格或者颜色变更的时候
- (void)_updateWithSelectedChanged{
    //根据sku和color的组合来查询价格等信息
    NSArray * prices = self.detailModel.g_price;
    if (self.detailModel.g_color.count == 0) { //没有color选项
        if (!self.skuData) {//没有选择任何skuData,重置库存和价格
            self.moneyLabel.text = [NSString stringWithFormat:@"￥%@",self.detailModel.gprice];
            self.amountLabel.text = @"库存：0";
            self.kucun = 0;
            self.fieldsData = nil;
            self.currentPrice = 0;
            
            return;
        }
        NSString * skuId = [self.skuData safeStringForKey:@"id"];
        NSString * skuValue = [self.skuData safeStringForKey:@"value"];
        [prices enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSArray * fields = [obj objectForKey:@"fields"];
            if ([fields isKindOfClass:[NSArray class]]) {
                for (int i = 0; i< fields.count; i++) {
                    NSString * sid = [fields[i] safeStringForKey:@"id"];
                    NSString * sv = [fields[i] safeStringForKey:@"value"];
                    if ([sid isEqualToString:skuId] && [skuValue isEqualToString:sv]) {//找到组合值
                        id inputs = [obj objectForKey:@"inputs"];
                        NSString * money = [inputs safeStringForKey:@"price"];
                        NSString * kucun = [inputs safeStringForKey:@"mvalue"];
                        self.moneyLabel.text = [NSString stringWithFormat:@"￥%@",money];
                        self.amountLabel.text = [NSString stringWithFormat:@"库存：%@",kucun];
                        self.kucun = [kucun integerValue];
                        self.fieldsData = prices[idx];
                        self.currentPrice = money;
                        *stop = YES;
                        break;
                    }
                }
            }
        }];
    }else if (self.detailModel.g_sku.count == 0){//没有sku选项
        if (!self.colorData) {//没有选择任何skuData,重置库存和价格
            self.moneyLabel.text = [NSString stringWithFormat:@"￥%@",self.detailModel.gprice];
            self.amountLabel.text = @"库存：0";
            self.kucun = 0;
            self.fieldsData = nil;
            self.currentPrice = 0;

            return;
        }
        NSString * skuId = [self.colorData safeStringForKey:@"id"];
        NSString * skuValue = [self.colorData safeStringForKey:@"value"] ;
        [prices enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSArray * fields = [obj objectForKey:@"fields"];
            if ([fields isKindOfClass:[NSArray class]]) {
                for (int i = 0; i< fields.count; i++) {
                    NSString * sid = [fields[i] safeStringForKey:@"id"];
                    NSString * sv = [fields[i] safeStringForKey:@"value"];
                    if ([sid isEqualToString:skuId] && [skuValue isEqualToString:sv]) {//找到组合值
                        id inputs = [obj objectForKey:@"inputs"];
                        NSString * money = [inputs safeStringForKey:@"price"];
                        NSString * kucun = [inputs safeStringForKey:@"quantity"];
                        self.moneyLabel.text = [NSString stringWithFormat:@"￥%@",money];
                        self.amountLabel.text = [NSString stringWithFormat:@"库存：%@",kucun];
                        self.kucun = [kucun integerValue];
                        self.fieldsData = prices[idx];
                        self.currentPrice = money;
                        *stop = YES;
                        break;
                    }
                }
            }
        }];
    }else{                              //既有sku又有color
        if (!self.colorData || !self.skuData) {     //其中一个缺失，就表明没有数据
            self.moneyLabel.text = [NSString stringWithFormat:@"￥%@",self.detailModel.gprice];
            self.amountLabel.text = @"库存：0";
            self.kucun = 0;
            self.fieldsData = nil;
            self.currentPrice = 0;

            return;
        }
        
        NSString * skuId = [self.skuData safeStringForKey:@"id"];
        NSString * skuValue = [self.skuData safeStringForKey:@"value"] ;
        NSString * colorId = [self.colorData safeStringForKey:@"id"];
        NSString * colorValue = [self.colorData safeStringForKey:@"value"];
        [prices enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSArray * fields = [obj objectForKey:@"fields"];
            if ([fields isKindOfClass:[NSArray class]]) {
                if (fields.count == 2) {
                    NSString * sid = [fields[0] safeStringForKey:@"id"];//颜色id
                    NSString * sv = [fields[0] safeStringForKey:@"value"] ;//颜色值
                    NSString * sid1 = [fields[1] safeStringForKey:@"id"];   //skuID
                    NSString * sv1 = [fields[1] safeStringForKey:@"value"] ;//sku值
                    if ([sid isEqualToString:colorId] && [colorValue isEqualToString:sv] && [sid1 isEqualToString:skuId] && [skuValue isEqualToString:sv1]) {//找到组合值
                        id inputs = [obj objectForKey:@"inputs"];
                        NSString * money = [inputs safeStringForKey:@"price"];
                        NSString * kucun = [inputs safeStringForKey:@"mvalue"];
                        self.moneyLabel.text = [NSString stringWithFormat:@"￥%@",money];
                        self.amountLabel.text = [NSString stringWithFormat:@"库存：%@",kucun];
                        self.kucun = [kucun integerValue];
                         self.fieldsData = prices[idx];
                        self.currentPrice = money;
                        *stop = YES;
                    }
                }
            }
        }];
    }
}

- (void)bgTouched{
    //背景点击,x点击
    [UIView animateWithDuration:.2 animations:^{
        self.bgWhiteView.transform = CGAffineTransformMakeTranslation(0, ScreenHeight * .7);
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)setKucun:(NSInteger)kucun{
    _kucun = kucun;
    //更新库存，则更新文本
    NSInteger textNumber = [self.addCountView.textField.text integerValue];
    if (textNumber > kucun) {
        self.addCountView.textField.text = [NSString stringWithFormat:@"%ld",kucun];
    }
}

@end

@interface GoodsSKUChooseView()

@property (nonatomic,strong) UILabel * titleLabel;
@property (nonatomic,strong) NSMutableArray<UIButton *> * itemBtns;
@property (nonatomic,strong) NSMutableArray * items;


@end

@implementation GoodsSKUChooseView

- (instancetype)init{
    if (self = [super init]) {
        self.titleLabel = [UILabel new];
        self.titleLabel.font = [UIFont systemFontOfSize:14];
        self.titleLabel.textColor = [UIColor blackColor];
        [self addSubview:self.titleLabel];
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(12);
            make.top.equalTo(self).offset(5);
        }];
        self.items = [NSMutableArray array];
        self.itemBtns = [NSMutableArray array];
    }
    return self;
}

- (void)loadItems:(NSArray *)items{
    if (items.count > 0) {
        NSString * title = [items[0] objectForKey:@"title"];
        self.titleLabel.text = title;
    }
    self.items = [items mutableCopy];
    for (int i = 0; i < items.count; i++) {
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        NSString * title = [items[i] objectForKey:@"text"];
        [btn setTitle:title forState:UIControlStateNormal];
        btn.backgroundColor = [UIColor colorWithHex:0xf6f6f6 alpha:1];
        [btn setTitleColor:[UIColor blackTextColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor ThemeColor] forState:UIControlStateSelected];
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        btn.layer.cornerRadius = 15;
        btn.layer.borderColor = [UIColor clearColor].CGColor;
        btn.layer.borderWidth = 1;
        [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = i;
        [self addSubview:btn];
        [self.itemBtns addObject:btn];
    }
    __block CGFloat maxWidth = 12;
    __block MASViewAttribute * leftAttr = self.mas_left;
    __block MASViewAttribute * topAttr = self.titleLabel.mas_bottom;
    [self.itemBtns enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CGSize size = [obj.titleLabel.text sizeWithFont:[UIFont systemFontOfSize:14] maxSize:CGSizeMake(ScreenWidth - 24, 100)];
        maxWidth += size.width + 44;
        if (maxWidth >= ScreenWidth) {
            maxWidth = 12;
            leftAttr = self.mas_left;
            if (idx == 0) {
                topAttr = self.titleLabel.mas_bottom;
            }else{
                topAttr = self.itemBtns[idx - 1].mas_bottom;
            }
        }
        [obj mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(leftAttr).offset(12);
            make.top.equalTo(topAttr).offset(15);
            make.width.equalTo(@(size.width + 20));
            make.height.equalTo(@30);
            if (idx == self.items.count - 1 ) {
                make.bottom.equalTo(self).offset(-10);
            }
        }];
        leftAttr = obj.mas_right;
       
    }];
}

- (void)btnClicked:(UIButton * )btn{
    if (btn.isSelected) {
        btn.selected = NO;
        btn.layer.borderColor = [UIColor clearColor].CGColor;
        btn.backgroundColor = [UIColor colorWithHex:0xf6f6f6 alpha:1];
        if (self.didSelectItem) {
            self.didSelectItem(nil);    //全未选中
        }
        return;
    }
    for (int i = 0; i < self.itemBtns.count; i++) {
        if (self.itemBtns[i].isSelected) {
            self.itemBtns[i].selected = NO;
            self.itemBtns[i].layer.borderColor = [UIColor clearColor].CGColor;
            self.itemBtns[i].backgroundColor = [UIColor colorWithHex:0xf6f6f6 alpha:1];
            break;
        }
    }
    btn.selected = YES;
    btn.backgroundColor = [UIColor colorWithHex:0xfff6f4 alpha:1];
    btn.layer.borderColor = [UIColor ThemeColor].CGColor;
    __weak typeof(self) weakSelf = self;
    if (self.didSelectItem) {
        self.didSelectItem(weakSelf.items[btn.tag]);
    }
    
}


@end


